package com.refid.api.thread;

import java.io.InputStream;
import java.util.Arrays;

import com.refid.api.cmd.Cmd;
import com.refid.api.hander.ReadHander;

import android.util.Log;

/**
 * 蓝牙输入流线程
 * 
 * @author lh
 *
 */
public class BuleReadThread extends Thread {
	private String LOG_TAG = getClass().getName();
	private static final int BUFFER_SIZE = 1024 * 300;
	private Integer readTimeOut = 500;
	private InputStream is;
	private ReadHander hander;
	private Cmd cmd;

	/**
	 * @param is          输入数据流
	 * @param cmd         处理16进制字符串命令
	 * @param hander      处理16进制字符串句柄
	 * @param readTimeOut 输入流数据等待超时时间,超过此时间认为没有数据流输入
	 * @param islog       是否有记录日志
	 */
	public BuleReadThread(InputStream is, Cmd cmd, ReadHander hander, Integer readTimeOut) {
		this.is = is;
		this.cmd = cmd;
		this.hander = hander;
		if (readTimeOut != null && readTimeOut > 10) {
			this.readTimeOut = readTimeOut;
		}
	}

	/**
	 * 设置数据流
	 * 
	 * @param is 输入数据流
	 */
	public void setIs(InputStream is) {
		this.is = is;
	}

	/**
	 * 得到输入数据流
	 * 
	 * @return
	 */
	public InputStream getIs() {
		return is;
	}

	@Override
	public void run() {
		int num = 0;// 读取的字节流数据。
		byte[] buffer = new byte[BUFFER_SIZE];// 一次读取最大缓存
		byte[] data = null;// 临时数据
		long now = System.currentTimeMillis();// 最后读取数据流时间时间戳
		long st = System.currentTimeMillis();// 当前读取数据花费时间时间戳
		StringBuilder sb = new StringBuilder();// 当前读取数据16进制字符串
		String hexs = null;
		while (true) {
			try {
				while (is.available() == 0) {
					if (System.currentTimeMillis() - now > readTimeOut) {// && sb.length() > 0
						hander.doRst(cmd, sb.toString(), System.currentTimeMillis() - st);
						sb = new StringBuilder();
						st = System.currentTimeMillis();
						now = System.currentTimeMillis();
					}
				}
				while (true) {
					num = is.read(buffer); // 读入数据
					data = Arrays.copyOfRange(buffer, 0, num);
					hexs = cmd.byteToHex(data);
					if (sb.length() > 0)
						sb.append(" ");
					sb.append(hexs);
					now = System.currentTimeMillis();
					if (is.available() == 0) {
						break; // 短时间没有数据才跳出进行显示
					}
				}
			} catch (Exception e) {
				Log.e(LOG_TAG, "thread error.", e);
				try {
					String msg = e.getMessage();
					if (is == null || msg.toUpperCase().contains("socket closed".toUpperCase())) {
						Log.e(LOG_TAG, "thread error break!", e);
						buffer = null;
						break;
					}
				} catch (Exception ex) {
				}
			}
		}
	}

}
